#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct RouteEntry
{
    string network;
    int hops;
    string nextHop;
};

vector<RouteEntry> ripUpdate(const vector<RouteEntry> &originalTable,
                             const vector<RouteEntry> &receivedTable,
                             const string &sender)
{
    vector<RouteEntry> newTable = originalTable;

    map<string, pair<int, string>> originalMap;
    for (const auto &entry : originalTable)
    {
        originalMap[entry.network] = {entry.hops, entry.nextHop};
    }

    for (const auto &receivedEntry : receivedTable)
    {
        string net = receivedEntry.network;
        int newHops = receivedEntry.hops + 1;
        string newNextHop = sender;

        if (originalMap.find(net) == originalMap.end())
        {
            newTable.push_back({net, newHops, newNextHop});
        }
        else if (newHops < originalMap[net].first)
        {
            for (auto &entry : newTable)
            {
                if (entry.network == net)
                {
                    entry.hops = newHops;
                    entry.nextHop = newNextHop;
                    break;
                }
            }
        }
    }

    return newTable;
}

void printRouteTable(const vector<RouteEntry> &table)
{
    cout << "Network\tHops\tNext Hop" << endl;
    cout << "-----------------------" << endl;
    for (const auto &entry : table)
    {
        cout << entry.network << "\t" << entry.hops << "\t" << entry.nextHop << endl;
    }
}

int main()
{
    vector<RouteEntry> originalTable = {
        {"N1", 1, "R1"},
        {"N2", 0, "direct"},
        {"N3", 6, "R4"},
        {"N4", 8, "R5"}};

    vector<RouteEntry> receivedTable = {
        {"N2", 2, "R5"},
        {"N3", 3, "R6"},
        {"N4", 7, "R7"},
        {"N5", 3, "R8"}};

    cout << "Original Routing Table:" << endl;
    printRouteTable(originalTable);

    vector<RouteEntry> updatedTable = ripUpdate(originalTable, receivedTable, "R2");

    cout << "\nUpdated Routing Table:" << endl;
    printRouteTable(updatedTable);

    return 0;
}